package com.bbs.core.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import com.bbs.core.model.Post;
import com.bbs.core.model.Reply;
import com.bbs.core.model.User;
import com.bbs.core.service.MessageService;
import com.bbs.core.service.PostService;
import com.bbs.core.service.UserService;
import com.bbs.core.dao.PostDao;
import com.bbs.core.dao.ReplyDao;
import com.bbs.core.dao.TopicDao;

@Service(value = "postService")
public class PostServiceImpl implements PostService{
	
	@Autowired
	private PostDao postDao;
	
	@Autowired
	private TopicDao topicDao;
	
	@Autowired
	private ReplyDao replyDao;
	
	@Autowired
	private UserService userService;
	

	@Override
	public Post selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Post> findAllPosts() {
		return postDao.selectAllPost();
	}
	
	@Override
	public List<Post> getPostsByTopicId(Integer topicId) {
//		postDao.getPosts(query, topicId);
		List<Post> selectAllPost = postDao.selectPostByTopicId(topicId);
		if(!selectAllPost.isEmpty()){
			for (Post post : selectAllPost) {
				List<Reply> replys = replyDao.selectReplyByPostId(post.getId());
				for(Reply reply : replys){
					User userReply = userService.selectByPrimaryKey(reply.getUserId());
					reply.setUser(userReply);
				}
				User userPost = userService.selectByPrimaryKey(post.getUserId());
				post.setReplys (replys);
				post.setUser(userPost);
			}
		}
		return selectAllPost;
	}

	@Override
	@CacheEvict(cacheNames="TOPIC", allEntries=true)
	public void savePost(Post post, User user) {
		post.setUserId(user.getId());
		postDao.insert(post);
		userService.addPostScore(user.getId());
	}
	
	@Override
	@CacheEvict(cacheNames="TOPIC", allEntries=true)
	public void deletePost(int id) {
		replyDao.deleteByPostId(id);
	}

	@Override
	public void updateByPrimaryKeySelective(Post record) {
		postDao.updateByPrimaryKeySelective(record);
		
	}

}
